package com.qimu.saiyou.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qimu.saiyou.annotation.AuthCheck;
import com.qimu.saiyou.common.BaseResponse;
import com.qimu.saiyou.common.DeleteRequest;
import com.qimu.saiyou.common.ErrorCode;
import com.qimu.saiyou.common.ResultUtils;
import com.qimu.saiyou.constant.UserConstant;
import com.qimu.saiyou.exception.BusinessException;
import com.qimu.saiyou.exception.ThrowUtils;
import com.qimu.saiyou.model.dto.competeexam.CompeteExamAddRequest;
import com.qimu.saiyou.model.dto.competeexam.CompeteExamQueryRequest;
import com.qimu.saiyou.model.dto.competeexam.CompeteExamUpdateRequest;
import com.qimu.saiyou.model.dto.competeexam.StartTheExamRequest;
import com.qimu.saiyou.model.dto.useranswer.UserPaperAnswerRequest;
import com.qimu.saiyou.model.entity.*;
import com.qimu.saiyou.model.vo.CompeteExamVO;
import com.qimu.saiyou.model.vo.UserPaperVo;
import com.qimu.saiyou.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 试卷
 *
 *@author: FeiXiang
 * 
 */
@RestController
@RequestMapping("/competeExam")
@Slf4j
public class CompeteExamController {
    @Resource
    private CompetitionService competitionService;
    @Resource
    private CompeteExamService competeExamService;
    @Resource
    private UserPaperAnswerService userPaperAnswerService;
    @Resource
    private UserPaperService userPaperService;
    @Resource
    private UserService userService;

    @Resource
    private ExamPaperService examPaperService;

    // region 增删改查

    /**
     * 创建
     *
     * @param competeExamAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(anyRole = {"admin", "teacher"})
    public BaseResponse<Long> addCompeteExam(@RequestBody CompeteExamAddRequest competeExamAddRequest, HttpServletRequest request) {
        if (competeExamAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        CompeteExam competeExam = new CompeteExam();
        BeanUtils.copyProperties(competeExamAddRequest, competeExam);
        competeExamService.validCompeteExam(competeExam, true);
        Long paperId = competeExam.getPaperId();
        ExamPaper paper = examPaperService.getById(paperId);
        ThrowUtils.throwIf(paper == null, ErrorCode.NOT_FOUND_ERROR, "试卷不存在");
        Long sumScore = Long.valueOf(paper.getTotalScore());
        if (ObjectUtils.isEmpty(competeExam.getQualifyScore())) {
            competeExam.setQualifyScore(Long.valueOf(paper.getQualifyScore()));
        } else {
            if (sumScore < competeExam.getQualifyScore()) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "及格分数不能大于试卷题目总分");
            }
        }

        competeExam.setTotalScore(sumScore);
        boolean result = competeExamService.save(competeExam);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newCompeteExamId = competeExam.getId();
        return ResultUtils.success(newCompeteExamId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(anyRole = {"admin", "teacher"})
    public BaseResponse<Boolean> deleteCompeteExam(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = deleteRequest.getId();
        // 判断是否存在
        CompeteExam oldCompeteExam = competeExamService.getById(id);
        ThrowUtils.throwIf(oldCompeteExam == null, ErrorCode.NOT_FOUND_ERROR);
        boolean b = competeExamService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param competeExamUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(anyRole = {"admin", "teacher"})
    public BaseResponse<Boolean> updateCompeteExam(@RequestBody CompeteExamUpdateRequest competeExamUpdateRequest) {
        if (competeExamUpdateRequest == null || competeExamUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        CompeteExam competeExam = new CompeteExam();
        BeanUtils.copyProperties(competeExamUpdateRequest, competeExam);
        // 参数校验
        competeExamService.validCompeteExam(competeExam, false);
        long id = competeExamUpdateRequest.getId();
        // 判断是否存在
        CompeteExam oldCompeteExam = competeExamService.getById(id);
        ThrowUtils.throwIf(oldCompeteExam == null, ErrorCode.NOT_FOUND_ERROR);
        Long paperId = competeExam.getPaperId();
        ExamPaper paper = examPaperService.getById(paperId);
        ThrowUtils.throwIf(paper == null, ErrorCode.NOT_FOUND_ERROR, "试卷不存在");
        Long sumScore = Long.valueOf(paper.getTotalScore());
        if (ObjectUtils.isEmpty(competeExam.getQualifyScore())) {
            competeExam.setQualifyScore(Long.valueOf(paper.getQualifyScore()));
        } else {
            if (sumScore < competeExam.getQualifyScore()) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "及格分数不能大于试卷题目总分");
            }
        }
        boolean result = competeExamService.updateById(competeExam);
        return ResultUtils.success(result);
    }

    @PostMapping("/open")
    @AuthCheck(anyRole = {"admin", "teacher"})
    public BaseResponse<Boolean> openExam(long id) {
        if (ObjectUtils.isEmpty(id) || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        CompeteExam competeExam = competeExamService.getById(id);
        ThrowUtils.throwIf(competeExam == null, ErrorCode.NOT_FOUND_ERROR);
        competeExam.setState("open");
        return ResultUtils.success(competeExamService.updateById(competeExam));
    }

    @PostMapping("/finish")
    @AuthCheck(anyRole = {"admin", "teacher"})
    public BaseResponse<Boolean> finishExam(long id) {
        if (ObjectUtils.isEmpty(id) || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        CompeteExam competeExam = competeExamService.getById(id);
        ThrowUtils.throwIf(competeExam == null, ErrorCode.NOT_FOUND_ERROR);
        competeExam.setState("finish");
        return ResultUtils.success(competeExamService.updateById(competeExam));
    }

    /**
     * 开始考试
     *
     * @param startTheExamRequest 身份证件
     * @return {@link BaseResponse}<{@link Boolean}>
     */
    @PostMapping("/startTheExam")
    public BaseResponse<UserPaper> startTheExam(@RequestBody StartTheExamRequest startTheExamRequest, HttpServletRequest request) {
        if (ObjectUtils.anyNull(startTheExamRequest, startTheExamRequest.getCompetitionId())
                || startTheExamRequest.getCompetitionId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long competitionId = startTheExamRequest.getCompetitionId();
        Competition competition = competitionService.getById(competitionId);
        if (competition == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "赛事不存在");
        }
        if ("end".equals(competition.getCompetitionStatus())) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "竞赛已结束");
        }
        if ("cancel".equals(competition.getCompetitionStatus())) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "竞赛已取消");
        }
        CompeteExam competeExam = competeExamService.getById(competition.getExamId());
        ThrowUtils.throwIf(competeExam == null, ErrorCode.NOT_FOUND_ERROR);
        String state = competeExam.getState();
        if ("create".equals(state)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "考试未开始");
        }
        if ("finish".equals(state)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "考试已结束");
        }
        User loginUser = userService.getLoginUser(request);
        competeExam.setCompetitionId(competition.getId());
        QueryWrapper<UserPaper> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(UserPaper::getCompetitionId, competition.getId())
                .eq(UserPaper::getUserId, loginUser.getId())
                .eq(UserPaper::getExamId, competeExam.getId());
        UserPaper userPaper = userPaperService.getOne(wrapper);
        if (ObjectUtils.isNotEmpty(userPaper) && "open".equals(userPaper.getState())) {
            return ResultUtils.success(userPaper, "您的考试已开始,正在前往中..");
        }
        if (ObjectUtils.isNotEmpty(userPaper) && ("finish".equals(userPaper.getState()) || "submit".equals(userPaper.getState()))) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "您已参加过或已提交该考试");
        }
        UserPaper newUserPaper = competeExamService.startTheExam(loginUser, competeExam);
        return ResultUtils.success(newUserPaper,"试卷创建成功，加载中...");
    }


    /**
     * 保存答案
     *
     * @param userPaperAnswerRequest 身份证件
     * @param request                要求
     * @return {@link BaseResponse}<{@link Boolean}>
     */
    @PostMapping("/saveAnswer")
    public BaseResponse<Boolean> saveAnswer(@RequestBody UserPaperAnswerRequest userPaperAnswerRequest, HttpServletRequest request) {
        if (ObjectUtils.anyNull(userPaperAnswerRequest, userPaperAnswerRequest.getId())
                || userPaperAnswerRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean res = competeExamService.saveAnswer(loginUser, userPaperAnswerRequest);
        return ResultUtils.success(res);
    }

    /**
     * 提交试卷
     *
     * @param userPaperAnswerRequest 身份证件
     * @param request                要求
     * @return {@link BaseResponse}<{@link Boolean}>
     */
    @PostMapping("/submitPaper")
    public BaseResponse<UserPaperVo> submitPaper(@RequestBody UserPaperAnswerRequest userPaperAnswerRequest, HttpServletRequest request) {
        if (ObjectUtils.anyNull(userPaperAnswerRequest,userPaperAnswerRequest.getId())
                || userPaperAnswerRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        UserPaperVo res = competeExamService.submitPaper(loginUser, userPaperAnswerRequest);
        return ResultUtils.success(res);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<CompeteExamVO> getCompeteExamVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        CompeteExam competeExam = competeExamService.getById(id);
        if (competeExam == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(CompeteExamVO.objToVo(competeExam));
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param competeExamQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<CompeteExam>> listCompeteExamByPage(@RequestBody CompeteExamQueryRequest competeExamQueryRequest) {
        long current = competeExamQueryRequest.getCurrent();
        long size = competeExamQueryRequest.getPageSize();
        Page<CompeteExam> competeExamPage = competeExamService.page(new Page<>(current, size),
                competeExamService.getQueryWrapper(competeExamQueryRequest));
        return ResultUtils.success(competeExamPage);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param competeExamQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<CompeteExamVO>> listCompeteExamVOByPage(@RequestBody CompeteExamQueryRequest competeExamQueryRequest,
                                                                     HttpServletRequest request) {
        long current = competeExamQueryRequest.getCurrent();
        long size = competeExamQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        size = 1000;
        Page<CompeteExam> competeExamPage = competeExamService.page(new Page<>(current, size),
                competeExamService.getQueryWrapper(competeExamQueryRequest));
        Page<CompeteExamVO> competeExamVOPage = new Page<>(competeExamPage.getPages(), competeExamPage.getSize(), competeExamPage.getTotal());
        List<CompeteExamVO> competeExamVOList = competeExamPage.getRecords().stream().map(CompeteExamVO::objToVo).collect(Collectors.toList());
        competeExamVOPage.setRecords(competeExamVOList);
        return ResultUtils.success(competeExamVOPage);
    }

    // endregion
}
